package gui.menu.stateDiagram;

import data.DataVector;
import data.stateDiagram.State;
import data.stateDiagram.Transition;
import gui.commands.CommandManager;
import gui.commands.stateDiagramCommands.DeleteTransitionCommand;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class DeleteTransitionForm extends JDialog {
	private JPanel contentPane;
	private JButton buttonOK;
	private JButton buttonCancel;
	private JComboBox transitionsComboBox;

	public DeleteTransitionForm() {
		setContentPane(contentPane);
		setModal(true);
		getRootPane().setDefaultButton(buttonOK);




		//setPreferredSize(new Dimension(300, 200));

		buttonOK.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				onOK();
			}
		});

		buttonCancel.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				onCancel();
			}
		});

// call onCancel() when cross is clicked
		setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);
		addWindowListener(new WindowAdapter() {
			public void windowClosing(WindowEvent e) {
				onCancel();
			}
		});

// call onCancel() on ESCAPE
		contentPane.registerKeyboardAction(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				onCancel();
			}
		}, KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);



		setUpComboBox();

		this.pack();
		this.setLocationRelativeTo(null);
	}

	private void setUpComboBox()
	{
		State state = (State)DataVector.getInstance().getActiveStateDiagram().getStateDiagram().getActiveState();

		for (Transition t : DataVector.getInstance().getActiveStateDiagram().getStateDiagram().getTransitions()) {
			if (t.getSource() == state) {
				transitionsComboBox.addItem(t);
			}
		}
	}

	private void onOK() {
		Transition t = (Transition)transitionsComboBox.getSelectedItem();

		CommandManager.getInstance().addAndExecuteStateDiagramCommand(
				new DeleteTransitionCommand(
						DataVector.getInstance().getActiveStateDiagram(),
						t
				)
		);

		dispose();
	}

	private void onCancel() {
// add your code here if necessary
		dispose();
	}
}
